package top.humbleyuan.dp;

/**
 * @Author: yuanhuanghui
 * @Date: 2020-08-03
 * @Time: 17:08
 * @Description: 编辑距离
 */
public class LeetCode_72 {
    public static void main(String[] args) {
        // abc ap
        String word1 = "abc";
        String word2 = "ap";

        // 初始化dp
        int[][] dp = new int[word1.length() + 1][word2.length() + 1];

        // 构造第一列
        for (int i = 0; i <= word1.length(); i++) {
            dp[i][0] = i;
        }

        // 构造第一行
        for (int i = 0; i <= word2.length(); i++) {
            dp[0][i] = i;
        }

        /**
         * dp递推式:
         * 增：dp[i][j] = dp[i - 1][j] + 1
         * 删：dp[i][j] = dp[i][j - 1] + 1
         * 改：dp[i][j] = dp[i - 1][j - 1] + 1
         * 计算时，取最小；
         * 如果当前字符相同，dp[i][j] = min(dp[i - 1][j - 1], dp[i - 1][j] + 1, dp[i][j - 1] + 1)
         */
        for (int i = 1; i <= word1.length(); i++) {
            for (int j = 1; j <= word2.length(); j++) {
                dp[i][j] = Math.min(dp[i - 1][j], Math.min(dp[i][j - 1], dp[i - 1][j - 1]));
                if(word1.charAt(i) == word2.charAt(j)) {
                    dp[i][j] = Math.min(dp[i - 1][j - 1], dp[i][j]);
                }
            }
        }

        System.out.println(dp[word1.length()][word2.length()]);
    }
}
